package com.dj.product.k2faas.jpa.config;

import net.ttddyy.dsproxy.support.ProxyDataSource;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * Created by 丁建 on 2025/9/24 15:13
 */
@Component
@ConditionalOnProperty(prefix = "logging.level.net.ttddyy.dsproxy.listener.logging", name = "SLF4JQueryLoggingListener", havingValue = "DEBUG")
public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean instanceof DataSource && !(bean instanceof ProxyDataSource)) {
            final ProxyFactory factory = new ProxyFactory(bean);
            factory.setProxyTargetClass(true);
            factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean).setDataSourceName("K2FaaS系统库"));
            return factory.getProxy();
        }
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }
}
